<?php

        // 获取login参数
        $login_org = isset($_GET['login']) ? $_GET['login'] : '';
        
        // 读取JSON文件
        $json_data = file_get_contents('B_2025.json');
        $orgs = json_decode($json_data, true);
        
        // 查找对应的组织信息
        $current_org = null;
        foreach ($orgs as $org) {
            if ($org['enorg'] === $login_org) {
                $current_org = $org;
                break;
            }
        }

        // 检查是否有表单提交
        $error_message = '';
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $name = isset($_POST['NAME']) ? $_POST['NAME'] : '';
            $mima = isset($_POST['MIMA']) ? $_POST['MIMA'] : '';
            
            // 验证name字段是英文且长度小于12个字符
            if (!preg_match('/^[A-Za-z\s]+$/', $name)) {
                $error_message = '姓名必须只包含英文字母和空格';
            } elseif (strlen($name) >= 12) {
                $error_message = '姓名长度必须小于12个字符';
            } elseif (!$current_org || $mima !== $current_org['sessionid']) {
                // 验证密码是否正确
                $error_message = '密钥不正确';
            } else {
                // 验证通过，设置cookie
                $expiry_time = time() + (30 * 24 * 60 * 60);
                setcookie('NAME', $name, $expiry_time, '/');
                setcookie('MIMA', $mima, $expiry_time, '/');
                setcookie('OR_KEY', $_POST['OR_KEY'], $expiry_time, '/');
                setcookie('ZP_KEY', $_POST['ZP_KEY'], $expiry_time, '/');
                setcookie('BIZY_KEY', $_POST['BIZY_KEY'], $expiry_time, '/');
                setcookie('cnorg', $current_org['cnorg'], $expiry_time, '/');
                setcookie('enorg', $current_org['enorg'], $expiry_time, '/');
                setcookie('sessiontime', $current_org['time'], $expiry_time, '/');
                
                // 重定向到main.php
                header('Location: main.php?login=' . urlencode($login_org));
                exit();
            }
        }

?>


<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo (isset($_COOKIE['cnorg']) && $_COOKIE['cnorg']) ? $_COOKIE['cnorg'].' - ' : ''; ?>AI管理系统 - 登录</title>
    <link href="https://cdn.staticfile.net/font-awesome/6.7.1/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.staticfile.net/tailwindcss/2.2.9/tailwind.min.css" rel="stylesheet">

    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;500;600;700&family=Noto+Sans+SC:wght@300;400;500;700&display=swap');
        
        body {
            font-family: 'Noto Sans SC', 'Noto Serif SC', Tahoma, Arial, Roboto, "Droid Sans", "Helvetica Neue", "Droid Sans Fallback", "Heiti SC", "Hiragino Sans GB", Simsun, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .login-container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 2.5rem;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 800px;
            border: 1px solid rgba(255, 255, 255, 0.5);
        }
        
        .login-header {
            text-align: center;
            margin-bottom: 2rem;
        }
        
        .login-header h1 {
            font-family: 'Noto Serif SC', serif;
            font-weight: 600;
            font-size: 2rem;
            color: #e91e63;
            margin-bottom: 0.5rem;
            letter-spacing: 1px;
        }
        
        .login-header p {
            color: #666;
            font-size: 0.9rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
            position: relative;
        }
        
        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: #333;
            font-size: 0.9rem;
        }
        
        .input-wrapper {
            position: relative;
        }
        
        .form-input {
            width: 100%;
            padding: 0.75rem 2.5rem 0.75rem 1rem;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-size: 1rem;
            transition: all 0.3s ease;
            background-color: #fafafa;
        }
        
        .form-input:focus {
            outline: none;
            border-color: #e91e63;
            box-shadow: 0 0 0 3px rgba(233, 30, 99, 0.1);
        }
        
        .toggle-password {
            position: absolute;
            right: 1rem;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #999;
            transition: color 0.3s ease;
        }
        
        .toggle-password:hover {
            color: #e91e63;
        }
        
        .login-btn {
            width: 100%;
            padding: 0.75rem;
            background: linear-gradient(135deg, #e91e63, #ec407a);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 1.1rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 1rem;
        }
        
        .login-btn:hover {
            background: linear-gradient(135deg, #d81b60, #e91e63);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(233, 30, 99, 0.4);
        }
        
        .login-btn:active {
            transform: translateY(0);
        }
        
        .footer-text {
            text-align: center;
            margin-top: 2rem;
            color: #999;
            font-size: 0.8rem;
        }
        
        /* 动画效果 */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .login-container {
            animation: fadeInUp 0.6s ease-out;
        }
        
        .error-message {
            color: red;
            text-align: center;
            margin-bottom: 1rem;
            font-weight: 500;
        }

        /* 密钥选项切换按钮样式 */
        .toggle-keys-btn {
            width: 100%;
            padding: 0.75rem;
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-size: 0.9rem;
            font-weight: 500;
            color: #666;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .toggle-keys-btn:hover {
            background: linear-gradient(135deg, #e9ecef, #dee2e6);
            border-color: #e91e63;
            color: #e91e63;
            transform: translateY(-1px);
        }

        /* 可选密钥区域样式 */
        .optional-keys-section {
            overflow: hidden;
            max-height: 0;
            opacity: 0;
            transition: all 0.3s ease-out;
        }

        .optional-keys-section.show {
            max-height: 800px;
            opacity: 1;
            margin-top: 1rem;
        }

        /* 图标旋转动画 */
        #toggleIcon {
            transition: transform 0.3s ease;
        }

        #toggleIcon.rotate {
            transform: rotate(180deg);
        }

        /* 模型选择器样式 */
        .model-selector {
            display: flex;
            flex-wrap: wrap;
            gap: 0.75rem;
            margin-bottom: 1rem;
        }

        .model-option {
            position: relative;
        }

        .model-option input[type="radio"] {
            position: absolute;
            opacity: 0;
            cursor: pointer;
        }

        .model-label {
            display: flex;
            align-items: center;
            cursor: pointer;
            padding: 0.5rem 1rem;
            border: 2px solid #e0e0e0;
            border-radius: 25px;
            background-color: #fafafa;
            transition: all 0.3s ease;
            font-size: 0.9rem;
            font-weight: 500;
            color: #666;
        }

        .model-label:hover {
            border-color: #e91e63;
            background-color: #fff5f7;
            transform: translateY(-1px);
        }

        .model-option input[type="radio"]:checked + .model-label {
            border-color: #e91e63;
            background: linear-gradient(135deg, #e91e63, #ec407a);
            color: white;
            box-shadow: 0 2px 8px rgba(233, 30, 99, 0.3);
        }

        .model-radio {
            width: 16px;
            height: 16px;
            border: 2px solid #ccc;
            border-radius: 50%;
            margin-right: 0.5rem;
            position: relative;
            transition: all 0.3s ease;
        }

        .model-option input[type="radio"]:checked + .model-label .model-radio {
            border-color: white;
            background-color: white;
        }

        .model-option input[type="radio"]:checked + .model-label .model-radio::after {
            content: '';
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #e91e63;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        .model-name {
            font-weight: 500;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-header">
            <h1><i class="fas fa-brain mr-2"></i><?php echo (isset($_COOKIE['cnorg']) && $_COOKIE['cnorg']) ? $_COOKIE['cnorg'].' - ' : ''; ?>AI 管理系统</h1>
            <p>请输入您的系统密钥进行身份验证</p>
        </div>
        
        <?php
        
        // 如果没有找到对应的组织，显示错误信息
        if (!$current_org) {
            echo '<div style="color: red; text-align: center; margin-bottom: 1rem;">无效的组织参数</div>';
        }
        
        // 显示错误信息
        if ($error_message) {
            echo '<div class="error-message">' . $error_message . '</div>';
        }
        ?>
        
        <form id="loginForm" action="main.php?login=<?php echo $login_org; ?>" method="POST">
            <div class="form-group">
                <label for="name" class="form-label">英文姓名或ID【必填】</label>
                <div class="input-wrapper">
                    <input type="username" id="name" name="NAME" class="form-input" required>
                    <i class="fas fa-eye toggle-password" data-target="name"></i>
                </div>
            </div>
            <div class="form-group">
                <label for="mima" class="form-label"><?php echo (isset($_COOKIE['cnorg']) && $_COOKIE['cnorg']) ? $_COOKIE['cnorg'].' - ' : ''; ?>组织密码【必填】</label>
                <div class="input-wrapper">
                    <input type="password" id="mima" name="MIMA" class="form-input" required>
                    <i class="fas fa-eye toggle-password" data-target="mima"></i>
                </div>
            </div>

            <!-- 密钥选项切换按钮 -->
            <div class="form-group">
                <button type="button" id="toggleKeys" class="toggle-keys-btn">
                    <i class="fas fa-key mr-2"></i>
                    <span id="toggleText">展开高级密钥设置</span>
                    <i class="fas fa-chevron-down ml-2" id="toggleIcon"></i>
                </button>
            </div>

            <!-- 可选密钥输入区域 -->
            <div id="optionalKeys" class="optional-keys-section">

                <div class="form-group">
                    <label for="bizy_key" class="form-label">BizyAIR - 工作流API密钥</label>
                    <div class="input-wrapper">
                        <input type="password" id="bizy_key" name="BIZY_KEY" class="form-input">
                        <i class="fas fa-eye toggle-password" data-target="bizy_key"></i>
                    </div>
                </div>

                <div class="form-group">
                    <label for="or_key" class="form-label">Nano外网修图 - OR路由器密钥</label>
                    <div class="input-wrapper">
                        <input type="password" id="or_key" name="OR_KEY" class="form-input">
                        <i class="fas fa-eye toggle-password" data-target="or_key"></i>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">AI模型平台 API密钥输入</label>

                    <!-- 模型选择器 -->
                    <div class="model-selector">
                        <div class="model-option">
                            <input type="radio" id="model_zp" name="ai_model" value="zp" checked>
                            <label for="model_zp" class="model-label">
                                <span class="model-radio"></span>
                                <span class="model-name">智谱AI</span>
                            </label>
                        </div>
                        <div class="model-option">
                            <input type="radio" id="model_dp" name="ai_model" value="dp">
                            <label for="model_dp" class="model-label">
                                <span class="model-radio"></span>
                                <span class="model-name">DeepSeek</span>
                            </label>
                        </div>
                        <div class="model-option">
                            <input type="radio" id="model_db" name="ai_model" value="db">
                            <label for="model_db" class="model-label">
                                <span class="model-radio"></span>
                                <span class="model-name">豆包</span>
                            </label>
                        </div>
                        <div class="model-option">
                            <input type="radio" id="model_yb" name="ai_model" value="yb">
                            <label for="model_yb" class="model-label">
                                <span class="model-radio"></span>
                                <span class="model-name">元宝</span>
                            </label>
                        </div>
                        <div class="model-option">
                            <input type="radio" id="model_bd" name="ai_model" value="bd">
                            <label for="model_bd" class="model-label">
                                <span class="model-radio"></span>
                                <span class="model-name">文心一言</span>
                            </label>
                        </div>
                    </div>

                    <!-- API密钥输入框 -->
                    <div class="input-wrapper" style="margin-top: 1rem;">
                        <input type="password" id="ai_model_key" name="AI_MODEL_KEY" class="form-input" placeholder="请输入所选模型的API密钥">
                        <i class="fas fa-eye toggle-password" data-target="ai_model_key"></i>
                    </div>

                    <!-- 隐藏字段用于存储各个模型的密钥 -->
                    <input type="hidden" id="zp_key" name="ZP_KEY">
                    <input type="hidden" id="dp_key" name="DP_KEY">
                    <input type="hidden" id="db_key" name="DB_KEY">
                    <input type="hidden" id="yb_key" name="YB_KEY">
                    <input type="hidden" id="bd_key" name="BD_KEY">
                </div>
            </div>
            
            <button type="submit" class="login-btn">
                <i class="fas fa-sign-in-alt mr-2"></i>登录<?php echo (isset($_COOKIE['cnorg']) && $_COOKIE['cnorg']) ? $_COOKIE['cnorg'].' - ' : ''; ?>AI系统
            </button>
        </form>
        
        <div class="footer-text">
            <p>© 2025-2035                 <i class="fas fa-sign-in-alt mr-2"></i>登录<?php echo (isset($_COOKIE['cnorg']) && $_COOKIE['cnorg']) ? $_COOKIE['cnorg'].' - ' : ''; ?>AI系统
AI管理系统 | 信息安全保护</p>
        </div>
    </div>

    <script>
        // 密码显示/隐藏切换功能
        document.querySelectorAll('.toggle-password').forEach(toggle => {
            toggle.addEventListener('click', function() {
                const targetId = this.getAttribute('data-target');
                const input = document.getElementById(targetId);
                
                if (input.type === 'password') {
                    input.type = 'text';
                    this.classList.remove('fa-eye');
                    this.classList.add('fa-eye-slash');
                } else {
                    input.type = 'password';
                    this.classList.remove('fa-eye-slash');
                    this.classList.add('fa-eye');
                }
            });
        });
        
        // 从Cookie中读取保存的密钥
        function getCookie(name) {
            const value = `; ${document.cookie}`;
            const parts = value.split(`; ${name}=`);
            if (parts.length === 2) return parts.pop().split(';').shift();
            return '';
        }

        // 模型密钥存储对象
        const modelKeys = {
            zp: '',
            dp: '',
            db: '',
            yb: '',
            bd: ''
        };

        // 当前选中的模型
        let currentModel = 'zp';

        // 模型切换功能
        function handleModelChange() {
            const selectedModel = document.querySelector('input[name="ai_model"]:checked').value;
            const aiModelKeyInput = document.getElementById('ai_model_key');

            // 保存当前模型的密钥
            modelKeys[currentModel] = aiModelKeyInput.value;

            // 切换到新模型
            currentModel = selectedModel;

            // 显示新模型的密钥
            aiModelKeyInput.value = modelKeys[currentModel] || '';
        }

        // 初始化模型密钥（从Cookie读取）
        function initializeModelKeys() {
            modelKeys.zp = getCookie('ZP_KEY') || '';
            modelKeys.dp = getCookie('DP_KEY') || '';
            modelKeys.db = getCookie('DB_KEY') || '';
            modelKeys.yb = getCookie('YB_KEY') || '';
            modelKeys.bd = getCookie('BD_KEY') || '';
        }

        // 密钥选项切换功能
        document.getElementById('toggleKeys').addEventListener('click', function() {
            const optionalKeys = document.getElementById('optionalKeys');
            const toggleText = document.getElementById('toggleText');
            const toggleIcon = document.getElementById('toggleIcon');

            if (optionalKeys.classList.contains('show')) {
                // 隐藏密钥区域
                optionalKeys.classList.remove('show');
                toggleText.textContent = '展开高级密钥设置';
                toggleIcon.classList.remove('rotate');
            } else {
                // 显示密钥区域
                optionalKeys.classList.add('show');
                toggleText.textContent = '收起高级密钥设置';
                toggleIcon.classList.add('rotate');

                // 如果首次展开且有Cookie值，则自动填充
                if (!optionalKeys.hasAttribute('data-filled')) {
                    document.getElementById('or_key').value = getCookie('OR_KEY');
                    document.getElementById('bizy_key').value = getCookie('BIZY_KEY');

                    // 初始化模型密钥并设置第一个模型的值
                    initializeModelKeys();
                    document.getElementById('ai_model_key').value = modelKeys[currentModel] || '';

                    optionalKeys.setAttribute('data-filled', 'true');
                }
            }
        });

        // 添加模型切换事件监听器
        document.querySelectorAll('input[name="ai_model"]').forEach(radio => {
            radio.addEventListener('change', handleModelChange);
        });

        // AI模型密钥输入框变化时保存到当前模型
        document.getElementById('ai_model_key').addEventListener('input', function() {
            modelKeys[currentModel] = this.value;
        });

        // 页面加载时读取Cookie并填充基本表单
        document.addEventListener('DOMContentLoaded', function() {
            document.getElementById('name').value = getCookie('NAME');
            document.getElementById('mima').value = getCookie('MIMA');
        });
        
        // 表单提交时保存密钥到Cookie
        document.getElementById('loginForm').addEventListener('submit', function(e) {
            // 保存当前模型的密钥
            const aiModelKeyInput = document.getElementById('ai_model_key');
            modelKeys[currentModel] = aiModelKeyInput.value;

            // 保存每个密钥到Cookie，有效期30天
            const expiryDate = new Date();
            expiryDate.setDate(expiryDate.getDate() + 30);
            const expires = "expires=" + expiryDate.toUTCString();

            document.cookie = "NAME=" + document.getElementById('name').value + ";" + expires + ";path=/";
            document.cookie = "MIMA=" + document.getElementById('mima').value + ";" + expires + ";path=/";
            document.cookie = "OR_KEY=" + document.getElementById('or_key').value + ";" + expires + ";path=/";
            document.cookie = "BIZY_KEY=" + document.getElementById('bizy_key').value + ";" + expires + ";path=/";

            // 保存所有模型密钥到对应的隐藏字段和Cookie
            document.getElementById('zp_key').value = modelKeys.zp;
            document.getElementById('dp_key').value = modelKeys.dp;
            document.getElementById('db_key').value = modelKeys.db;
            document.getElementById('yb_key').value = modelKeys.yb;
            document.getElementById('bd_key').value = modelKeys.bd;

            document.cookie = "ZP_KEY=" + modelKeys.zp + ";" + expires + ";path=/";
            document.cookie = "DP_KEY=" + modelKeys.dp + ";" + expires + ";path=/";
            document.cookie = "DB_KEY=" + modelKeys.db + ";" + expires + ";path=/";
            document.cookie = "YB_KEY=" + modelKeys.yb + ";" + expires + ";path=/";
            document.cookie = "BD_KEY=" + modelKeys.bd + ";" + expires + ";path=/";
        });
    </script>
</body>
</html>